// pages/translate/translate.js
var plugin = requirePlugin("WechatSI")
let manager = plugin.getRecordRecognitionManager()
const db = wx.cloud.database()
const translate_db = db.collection('translate')
var util = require('../../libs/util.js');

Page({
  data: {
    recordPermission: 0,
    translateList: [],
    translating: {
      from_text: "请长按底部按钮说话...",
      to_text: "..."
    }
  },
  onLoad: function (options) {
    this._get_my_translate_db()
  },
  onShow() {
    this.getRecordPermission()
  },
  onShareAppMessage(res) {

  },
  getRecordPermission() {
    wx.getSetting().then(res => {
      //用户录音授权没有开启
      if (!res.authSetting['scope.record']) {
        //申请授权
        wx.authorize({
          scope: 'scope.record'
        }).then(res => {
          wx.showToast({
            title: '授权成功',
            icon: 'none'
          })
          this.setPermissionData(1)
          return 1
        }).catch(err => {
          this.setPermissionData(-1)
          console.error(err)
          return 0
        })
      } else {
        //授权已开启
        this.setPermissionData(1)
        console.log("record:授权已开启")
        return 1
      }
    }).catch(err => {
      console.error("调用getSetting失败", err)
    })
  },
  // 设置权限
  setPermissionData(val) {
    this.setData({
      recordPermission: val
    })
  },
  //--------------------------开始录音中文--------------------------
  startRecordChinese() {
    let result = this.getRecordPermission()
    if (!result) result
    this.addRecordListener(1)
    this.startRecord(1)
  },
  //--------------------------开始录音英文--------------------------
  startRecordEnglish() {
    let result = this.getRecordPermission()
    if (!result) result
    this.addRecordListener(2)
    this.startRecord(2)
  },
  //开始录音
  startRecord(flag) {
    var mLang = "zh_CN"
    if (flag != 1) {
      mLang = "en_US";
    }
    manager.start({
      lang: mLang
    })
    wx.showLoading({
      title: '正在聆听中...'
    })
  },
  //结束录音
  stopRecord(e) {
    // console.log("stopRecord", e)
    manager.stop()
    wx.hideLoading()
  },
  //录音监听
  addRecordListener(flag) {
    var lfrom = "zh_CN"
    var lto = "en_US"
    if (flag != 1) {
      lfrom = "en_US"
      lto = "zh_CN"
    }
    var _this = this
    manager.onRecognize = function (res) {
      console.log("onRecognize", res.result)
      _this.setTraslateText(res.result)
    }
    manager.onStop = function (res) {
      // console.log("record file path", res.tempFilePath)
      console.log("onStop", res.result)
      if (res.result)
        _this.setTraslateText(res.result)
      // console.log("textTranslate", lfrom, lto)
      _this.textTranslate(res.result, lfrom, lto)
    }
    manager.onStart = function (res) {
      console.log("onStart", res)
      _this.setTraslateText("正在输入中...")
      _this.pageScrollToBottom()
    }
    manager.onError = function (res) {
      console.log("onError", res)
    }
  },
  //设置翻译文字
  setTraslateText(from_text) {
    this.setData({
      translating: {
        from_text: from_text,
        to_text: "..."
      }
    })
  },
  //文本翻译
  textTranslate(text, lfrom, lto) {
    var _this = this
    plugin.translate({
      lfrom: lfrom,
      lto: lto,
      content: text,
      success: function (res) {
        if (res.retcode == 0) {
          console.log("translate", lto, res.result)
          _this.saveTranslateInfo(text, res.result)
          _this.textSpeech(res.result, lto)
        } else {
          console.warn("翻译失败", res)
        }
      },
      fail: function (res) {
        console.log("网络失败", res)
        _this.setTraslateText("网络错误，请重新输入")
      }
    })
  },
  //文本合成语音
  textSpeech(text, lto) {
    var _this = this
    plugin.textToSpeech({
      lang: lto,
      tts: true,
      content: text,
      success: function (res) {
        console.log("textToSpeech succ tts", res)
        _this.playAudio(res.filename)
      },
      fail: function (res) {
        console.log("textToSpeech fail tts", res)
      }
    })
  },
  //播放音频
  playAudio(audioPath) {
    const innerAudioContext = wx.createInnerAudioContext()
    innerAudioContext.autoplay = true
    innerAudioContext.src = audioPath
    innerAudioContext.onPlay(() => {
      console.log('开始播放')
    })
    innerAudioContext.onError((res) => {
      console.log(res.errMsg)
      console.log(res.errCode)
    })
  },
  // 获取容器高度，使页面滚动到容器底部
  pageScrollToBottom: function () {
    wx.createSelectorQuery().select('#translate_layout').boundingClientRect(function (rect) {
      // 使页面滚动到底部
      console.log(rect.height);
      wx.pageScrollTo({
        scrollTop: rect.height
      })
    }).exec()
  },
  // 获取数据库的我的翻译记录
  _get_my_translate_db: function () {
    translate_db.get({
      success: res => {
        console.log("translate_db", res.data[1])
        this.setData({
          translateList: res.data
        })
        this.pageScrollToBottom()
      }
    })
  },
  //保存翻译结果
  saveTranslateInfo(from_text, to_text) {
    var date_time = util.getDateTime()
    var translateInfo = {
      translate_time: date_time,
      from_text: from_text,
      to_text: to_text
    }
    this._add_my_translate_db(translateInfo)
  },
  // 添加我翻译到数据库
  _add_my_translate_db: function (translateObj) {
    var _this = this;
    translate_db.add({
        data: translateObj
      })
      .then(res => {
        console.log(res)
        //其他逻辑
        var oldTranslateList = _this.data.translateList
        translateObj._id = res._id
        oldTranslateList.push(translateObj)
        _this.setTraslateText(null)
        _this.setData({
          translateList: oldTranslateList
        })
      }).catch(err => {
        console.log(err)
      })
  },
  //列表长按监听
  handleLongPress(e) {
    console.log("handleLongPress", e)
    let selectId = e.currentTarget.dataset.id
    // 操作弹窗
    wx.showActionSheet({
      itemList: ['删除'],
    }).then(res => {
      // 提示弹窗
      wx.showModal({
        title: '提示',
        content: '确认删除？'
      }).then(res => {
        if (res.confirm)
          this._delete_my_translate_db(selectId)
      })
    }).catch(err => {
      console.error((err))
    })
  },
  // 删除数据库翻译的记录
  _delete_my_translate_db: function (translateId) {
    var _this = this;
    translate_db.doc(translateId).remove({
      success: function (res) {
        console.log(res)
        wx.showToast({
          title: '删除成功！'
        })
        // 删除本地数据
        var mTranslateList = _this.data.translateList
        for (var i = 0; i < mTranslateList.length; i++) {
          if (mTranslateList[i]._id === translateId) {
            mTranslateList.splice(i, 1);
          }
        }
        console.log(mTranslateList)
        _this.setData({
          translateList: mTranslateList
        })
      }
    })
  },
})